#include "configmanager.h"
#include <QSettings>
#include <QApplication>
#include <QStandardPaths>

ConfigManager::ConfigManager(QObject *parent)
    : QObject(parent)
    , settings(new QSettings(QSettings::UserScope, "RemoteMaster", "RemoteMaster"))
    , cacheEnabled(true)
{
}

ConfigManager::~ConfigManager()
{
    delete settings;
}

QVariant ConfigManager::getValue(const QString &key, const QVariant &defaultValue) const
{
    // 首先检查缓存
    if (cacheEnabled && cache.contains(key)) {
        return cache.value(key);
    }
    
    // 从设置中读取
    QVariant value = settings->value(key, defaultValue);
    
    // 更新缓存
    if (cacheEnabled) {
        cache[key] = value;
    }
    
    return value;
}

void ConfigManager::setValue(const QString &key, const QVariant &value)
{
    // 更新设置
    settings->setValue(key, value);
    
    // 更新缓存
    if (cacheEnabled) {
        cache[key] = value;
    }
}

QVariantMap ConfigManager::getAllConfig() const
{
    QVariantMap config;
    
    // 获取所有键
    QStringList keys = settings->allKeys();
    for (const QString &key : keys) {
        config[key] = settings->value(key);
    }
    
    return config;
}

void ConfigManager::setConfig(const QVariantMap &config)
{
    for (auto it = config.constBegin(); it != config.constEnd(); ++it) {
        settings->setValue(it.key(), it.value());
    }
    
    // 更新缓存
    if (cacheEnabled) {
        cache = config;
    }
}

void ConfigManager::beginGroup(const QString &group)
{
    settings->beginGroup(group);
}

void ConfigManager::endGroup()
{
    settings->endGroup();
}

QString ConfigManager::getLastHost() const
{
    return getValue("connection/last_host", "127.0.0.1").toString();
}

void ConfigManager::setLastHost(const QString &host)
{
    setValue("connection/last_host", host);
}

int ConfigManager::getLastPort() const
{
    return getValue("connection/last_port", 5900).toInt();
}

void ConfigManager::setLastPort(int port)
{
    setValue("connection/last_port", port);
}

bool ConfigManager::getFullscreenMode() const
{
    return getValue("display/fullscreen", false).toBool();
}

void ConfigManager::setFullscreenMode(bool fullscreen)
{
    setValue("display/fullscreen", fullscreen);
}

int ConfigManager::getTargetFps() const
{
    return getValue("performance/target_fps", 30).toInt();
}

void ConfigManager::setTargetFps(int fps)
{
    setValue("performance/target_fps", fps);
}